<template>
  <div>
    <el-drawer class="drawer" :title="title" :visible.sync="visible" size="50%" direction="rtl">
      <div class="container">
        <div class="container-body" ref="containerBody">
          <el-form ref="form" :model="form" label-width="120px" :rules="rules">
            <div class="section">
              <div class="section-title">基本信息</div>
              <div class="section-content">
                <div class="section-content-item">
                  <div class="section-content-item-label">
                    状态：
                  </div>
                  <div class="section-content-item-content">
                    <dict-tag :options="dict.type.coupon_state" :value="form.couponState"/>
                  </div>
                </div>
                <div class="section-content-item">
                  <div class="section-content-item-label">
                    所属机构：
                  </div>
                  <div class="section-content-item-content">
                    {{ form.tenantName }}
                  </div>
                </div>
                <div class="section-content-item" v-if="form.couponState === '6'">
                  <div class="section-content-item-label">
                    驳回原因：
                  </div>
                  <div class="section-content-item-content">
                    {{ form.rejectReason }}
                  </div>
                </div>
                <div class="section-content-item">
                  <div class="section-content-item-label">
                    优惠券类型：
                  </div>
                  <div class="section-content-item-content">
                    <dict-tag :options="dict.type.coupon_type" :value="form.couponType"/>
                  </div>
                </div>
                <div class="section-content-item">
                  <div class="section-content-item-label">
                    优惠券名称：
                  </div>
                  <div class="section-content-item-content">
                    {{ form.couponName }}
                  </div>
                </div>
                <div class="section-content-item">
                  <div class="section-content-item-label">
                    券码：
                  </div>
                  <div class="section-content-item-content">
                    {{ form.couponId }}
                  </div>
                </div>
                <div class="section-content-item">
                  <div class="section-content-item-label">
                    优惠券面额：
                  </div>
                  <div class="section-content-item-content">
                    {{ form.couponDenomination }}
                  </div>
                </div>
                <div class="section-content-item">
                  <div class="section-content-item-label">
                    标签：
                  </div>
                  <div class="section-content-item-content">
                    {{ form.couponLabel }}
                  </div>
                </div>
              </div>
            </div>
            <div class="section">
              <div class="section-title">规则范围</div>
              <div class="section-content">
                <div class="section-content-item">
                  <div class="section-content-item-label">
                    使用门槛：
                  </div>
                  <div class="section-content-item-content">
                    <span v-if="form.couponType === '2'">无门槛</span>
                    <span v-else>满{{ form.couponThreshold }}元可用</span>
                  </div>
                </div>
                <div class="section-content-item">
                  <div class="section-content-item-label">
                    活动时间：
                  </div>
                  <div class="section-content-item-content">
                    <span>{{ form.activityStartTime }} - {{ form.activityEndTime }}</span>
                  </div>
                </div>
                <div class="section-content-item">
                  <div class="section-content-item-label">
                    券使用有效期：
                  </div>
                  <div class="section-content-item-content">
                    <span v-if="form.validityPeriodType === '1'">活动时间内</span>
                    <span v-else>领取后{{ form.validityPeriodDay }}天内有效</span>
                  </div>
                </div>
                <div class="section-content-item">
                  <div class="section-content-item-label">
                    领取方式：
                  </div>
                  <div class="section-content-item-content">
                    {{ form.pickupMethodName }}
                    <el-button type="text" style="margin-left: 10px;" v-if="form.pickupMethod&&form.pickupMethod.includes('3')"
                               @click.stop="handleShowCode">查看核销码
                    </el-button>
                  </div>
                </div>
                <div class="section-content-item full-width">
                  <div class="section-content-item-label">
                    使用范围：
                  </div>
                  <div class="section-content-item-content">
                    <div style="display: flex;align-items: baseline;">
                      <dict-tag :options="dict.type.apply_scope" :value="form.applyScope"/>
                      <el-button style="margin-left: 10px;" v-if="form.applyScope === '2'" type="text"
                                 @click.stop="handleShowSelectHouse">已选（{{ form.couponHouseList.length }}）
                      </el-button>
                      <el-button style="margin-left: 10px;" v-if="form.applyScope === '3'" type="text"
                                 @click.stop="handleShowSelectArea">查看
                      </el-button>
                    </div>

                  </div>
                </div>
                <div class="section-content-item">
                  <div class="section-content-item-label">
                    是否与其他优惠券叠加使用：
                  </div>
                  <div class="section-content-item-content">
                    <span v-if="form.superpositionType === '0'">否</span>
                    <span v-else>是</span>
                  </div>
                </div>
                <div class="section-content-item">
                  <div class="section-content-item-label">
                    是否订单退款成功失效：
                  </div>
                  <div class="section-content-item-content">
                    <span v-if="form.refundLapsedType === '0'">否</span>
                    <span v-else>是</span>
                  </div>
                </div>
                <div class="section-content-item full-width">
                  <div class="section-content-item-label">
                    使用说明：
                  </div>
                  <div class="section-content-item-content" v-html="form.couponInstruction">
                  </div>
                </div>
              </div>
            </div>
          </el-form>
        </div>
        <div class="container-footer" v-if="isAudit">
          <el-button @click.stop="visible = false">取消</el-button>
          <el-button type="danger" @click.stop="handleReject">驳回</el-button>
          <el-button type="primary" @click.stop="handlePass">审核通过</el-button>
        </div>
      </div>
      <!--   选择房屋弹窗   -->
      <select-house :show.sync="showSelectHouse" :selectable="false" :isMultiple="true" :data="form"
                    :seleted-list="form.couponHouseList"
                    api-type="listRoomByAllocation" :api-params="apiParams"
                    @success="handleSelectHouseSuccess"></select-house>
      <!--   已选择区域弹窗   -->
      <el-dialog title="指定区域" :visible.sync="showSelectArea" width="600px" append-to-body>
        <el-table :data="seletedAreaList" row-key="id" :tree-props="{children: 'children'}">
          <el-table-column prop="name" label="省">
            <template slot-scope="scope" v-if="scope.row.parentId === '0'">{{ scope.row.name }}</template>
          </el-table-column>
          <el-table-column prop="name" label="市">
            <template slot-scope="scope" v-if="scope.row.parentId !== '0'">
              {{ scope.row.name }}
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>
    </el-drawer>
    <!-- 核销码弹窗 -->
    <el-dialog title="核销码" :visible.sync="showCode" width="600px" append-to-body>
      <el-table :data="form.couponVerificationList">
        <el-table-column prop="name" label="序号" width="50">
          <template slot-scope="scope">{{
              scope.$index + 1
            }}
          </template>
        </el-table-column>
        <el-table-column prop="verificationCode" label="核销码" />
        <el-table-column prop="verificationState" label="状态" width="100" >
          <template slot-scope="scope">
            <span v-if="scope.row.verificationState === '0'">未使用</span>
            <span v-else-if="scope.row.verificationState === '1'">已使用</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog title="驳回" :visible.sync="showRejectReason" width="400px" append-to-body>
      <el-form ref="acceptRejectForm" :model="acceptRejectForm" label-width="120px" label-position="top"
               :rules="rejectRules">
        <el-form-item label="驳回原因" prop="rejectReason">
          <el-input type="textarea" v-model="acceptRejectForm.rejectReason" placeholder="请输入驳回原因" show-word-limit
                    :maxlength="100" :rows="4"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.stop="showRejectReason = false">取 消</el-button>
        <el-button type="primary" @click.stop="handleRejectReason">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listDepartment} from "@/api/sys-enterprise";
import {areaInfo} from "@/api/system/config";
import selectHouse from "@/views/components/common/select-house/index.vue";
import {debounce} from "@/utils";
import {addCoupon, auditCoupon, editCoupon, getCouponDetail, getProvinceAndCity} from "@/api/marketing/coupon";

export default {
  name: "CouponAdd",
  dicts: ['apply_scope', 'coupon_state','coupon_type'],
  components: {
    selectHouse
  },
  props: {
    title: {
      type: String,
      default: "新增优惠券"
    },
    show: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      default: () => ({})
    },
    isAudit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // 选择房屋弹窗状态
      showSelectHouse: false,
      // 选择区域弹窗状态
      showSelectArea: false,
      // 核销码弹窗状态
      showCode: false,
      // 驳回弹窗状态
      showRejectReason: false,
      // 驳回表单数据
      acceptRejectForm: {
        couponId: "", //优惠券ID
        searchValue: "", //1是通过,其他不是
        rejectReason: "" //驳回原因
      },
      // 驳回表单验证规则
      rejectRules: {
        rejectReason: [
          {required: true, message: '请输入驳回原因', trigger: 'blur'},
        ]
      },
      // 选中房屋弹窗筛选条件数据
      apiParams: {
        apartmentState: "0", // 上架状态：0已上架 1已下架
        tenantId: "", // 所属机构ID
        houseIds: "", // 房源ID集合
      },
      // 机构列表
      tenantList: [],
      cityCode: [], //区域编码
      areaList: [], //区域列表
      // 已选择省市列表
      seletedAreaList: [],
      pickupMethod: [], //领取方式
      pickupMethodList: [
        {label: "领券中心", value: "1"},
        {label: "商品详情", value: "2"},
        {label: "核销码", value: "3"},
        {label: "指派", value: "4"}
      ], //领取方式列表
      // 表单数据
      form: {},
      // 表单验证规则
      rules: {
        couponName: [
          {required: true, message: '请输入优惠券名称', trigger: 'blur'},
          {min: 1, max: 20, message: '优惠券名称长度在 1 到 20 个字符', trigger: 'blur'}
        ],
        couponType: [
          {required: true, message: '请选择优惠券类型', trigger: 'change'}
        ],
        couponThreshold: [
          {required: true, message: '请输入使用门槛', trigger: 'blur'},
        ],
        tenantId: [
          {required: true, message: '请选择所属机构', trigger: 'change'}
        ],
        couponDenomination: [
          {required: true, message: '请输入优惠券面额', trigger: 'blur'},
          {
            validator: (rule, value, callback) => {
              if (value < 0.01) {
                callback(new Error('优惠券面额必须大于等于0.01'));
              } else if (value > 10000) {
                callback(new Error('优惠券面额必须小于等于10000'));
              } else {
                callback();
              }
            }, trigger: 'blur'
          }
        ],
        couponLabel: [
          {required: true, message: '请输入标签', trigger: 'blur'}
        ],
        totalCirculation: [
          {required: true, message: '请输入总发行量', trigger: 'blur'},
        ],
        activityTime: [
          {required: true, message: '请选择活动时间', trigger: 'change'}
        ],
        validityPeriodType: [
          {required: true, message: '请选择有效期类型', trigger: 'change'}
        ],
        validityPeriodDay: [
          {required: true, message: '请输入有效期天数', trigger: 'blur'},
          {type: 'number', message: '有效期天数必须为数字', trigger: 'blur'},
          {min: 1, max: 99999, message: '有效期天数必须在 1 到 99999 之间', trigger: 'blur'}
        ],
        applyScope: [
          {required: true, message: '请选择适用范围', trigger: 'change'},
          {
            validator: (rule, value, callback) => {
              if (value === '2' && !this.form.couponHouseList.length) {
                callback(new Error('请选择适用房源'));
              } else if (value === '3' && !this.form.cityCode) {
                callback(new Error('请选择适用区域'));
              } else {
                callback();
              }
            }, trigger: 'change'
          }
        ],
        cityCode: [
          {required: true, message: '请选择区域', trigger: 'change'}
        ],
        pickupMethod: [
          {required: true, message: '请选择领取方式', trigger: 'blur'},
          {
            validator: (rule, value, callback) => {
              if (this.pickupMethod.length === 0) {
                callback(new Error('请选择领取方式'));
              }
              if (this.pickupMethod.includes('3') && !this.form.verificationNumber) {
                callback(new Error('请输入核销码数量'));
              }
              callback();
            }, trigger: 'change'
          }
        ],
        verificationNumber: [
          {required: true, message: '请输入核销码数量', trigger: 'blur'},
          {type: 'number', message: '核销码数量必须为数字', trigger: 'blur'},
          {min: 1, max: 99999, message: '核销码数量必须在 1 到 99999 之间', trigger: 'blur'}
        ],
        couponInstruction: [
          {required: true, message: '请输入使用说明', trigger: 'blur'}
        ]
      }
    }
  },
  computed: {
    visible: {
      get() {
        return this.show
      },
      set(val) {
        this.$emit("update:show", val)
      }
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.$nextTick(() => {
          console.log('this.$refs', this.$refs.containerBody)
          this.$refs.containerBody.scrollTop = 0;
        })
        this.init();
      }
    }
  },
  created() {
    // this.getAreaInfo();
  },
  methods: {
    init() {
      // this.getDepartmentList();
      this.reset();
      if (this.data.couponId) {
        this.form = {...this.data}
        this.form['activityTime'] = [this.data.activityStartTime, this.data.activityEndTime];
        this.cityCode = this.data.cityCode ? this.data.cityCode.split(",") : [];
        this.pickupMethod = this.data.pickupMethod ? this.data.pickupMethod.split(",") : [];
      }
    },
    // 重置表单
    reset() {
      this.form = {
        tenantId: null, //机构ID
        couponName: "", //优惠券名称
        couponType: "1", //优惠价类型(1.满减券,2.无门槛券)
        couponState: "1", //优惠券状态(1.待提交,2.待审核,3.待开始,4.活动中,5.已结束,6.已驳回)
        couponDenomination: null, //优惠券面额
        couponThreshold: null, //使用门槛
        couponLabel: "", //优惠券标签
        totalCirculation: null, //总发行量
        activityTime: [], //活动时间
        activityStartTime: "", //活动开始时间
        activityEndTime: "", //活动结束时间
        validityPeriodType: "1", //有效期类型(1.活动时间内,2.领取几天内有效)
        validityPeriodDay: null, //领取天数内有效,validityPeriodType为2则传
        applyScope: "1", //使用范围(1.全场通用,2.指定房源,3.指定区域)
        cityCode: null, //区域编码,applyScope为3则传
        pickupMethod: "", //领取方式(1.领券中心,2.商品详情,3.核销码,4.指派)
        pickupMethodName: "", //领取方式名称
        verificationNumber: null, //核销码数量,pickupMethod为3则传
        superpositionType: "0", //是否叠加使用(0:否,1.是)
        refundLapsedType: "0", //退款成功失效(0:否,1.是)
        couponInstruction: null, //使用说明
        tenantName: null, //机构名称
        remainingNumber: null,
        couponHouseList: [] //优惠券关联房源数据集合,applyScope为2则传
      }
      this.cityCode = [];
      this.pickupMethod = [];
      this.resetForm("form");
    },
    // 获取区域信息
    getAreaInfo() {
      areaInfo().then((res) => {
        this.areaList = res.data;
      });
    },
    // 查询机构列表
    getDepartmentList() {
      listDepartment().then(response => {
        this.tenantList = response.data.map(item => {
          return {
            label: item.tenantName,
            value: item.tenantId
          }
        });
      });
    },
    // 展示已选择房屋弹窗
    handleShowSelectHouse() {
      this.apiParams.tenantId = this.form.tenantId;
      this.apiParams.houseIds = this.form.couponHouseList.map(item => item.houseId).join(",");
      this.showSelectHouse = true;
    },
    // 选择房源成功回调
    handleSelectHouseSuccess(val) {
      this.form.couponHouseList = val;
    },
    // 展示已选择区域弹窗
    handleShowSelectArea() {
      let params = {
        cityCodes: this.form.cityCode
      }
      getProvinceAndCity(params).then(response => {
        this.seletedAreaList = response.data;
        this.showSelectArea = true;
      });

    },
    // 展示核销码弹窗
    handleShowCode() {
      this.showCode = true;
    },
    // 驳回弹窗
    handleReject() {
      this.acceptRejectForm = {
        couponId: this.form.couponId,
        searchValue: "0",
        rejectReason: ""
      }
      this.showRejectReason = true;
    },
    // 驳回提交
    handleRejectReason() {
      this.$refs.acceptRejectForm.validate((valid) => {
        console.log('valid', valid)
        if (valid) {
          auditCoupon(this.acceptRejectForm).then(response => {
            this.$message.success(response.msg || "驳回成功");
            this.showRejectReason = false;
            this.visible = false;
            this.$emit("success");
          })
        }
      })
    },
    // 通过
    handlePass: debounce(function () {
      this.acceptRejectForm = {
        couponId: this.form.couponId,
        searchValue: "1",
        rejectReason: ""
      }
      this.$confirm('确认通过该优惠券吗？').then(() => {
        auditCoupon(this.acceptRejectForm).then(response => {
          this.$message.success(response.msg || "操作成功");
          this.visible = false;
          this.$emit("success");
          this.reset();
        }).catch((err) => {
          this.$message.error(err.msg || "操作失败");
        });
      }).catch(() => {
      });
    }, 1000, true),
    handleSubmit: debounce(function () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.form.couponId) {
            editCoupon(this.form).then(response => {
              this.$message.success(response.msg || "保存成功");
              this.visible = false;
              this.$emit("success");
              this.reset();
            })
          } else {
            addCoupon(this.form).then(response => {
              this.$message.success(response.msg || "保存成功");
              this.visible = false;
              this.$emit("success");
              this.reset();
            })
          }

        }
      });
    }, 1000, true),
  }
}
</script>

<style lang="scss" scoped>
.container {
  overflow: hidden;
  height: 100%;
  position: relative;

  .container-body {
    overflow-y: auto;
    height: 90%;
  }

  .container-footer {
    height: 10%;
    display: flex;
    align-items: center;
    border-top: 1px solid #e4e4e4;
    padding: 10px;
    justify-content: center;
  }
}

.section {
  padding: 10px;

  .section-title {
    padding: 8px 16px;
    background-color: #ecf8ff;
    border-radius: 4px;
    border-left: 5px solid #50bfff;
    margin-bottom: 20px;
    font-size: 16px;
    font-weight: bold;
  }

  .section-content {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-gap: 20px;

    .section-content-item {
      //display: grid;
      //grid-template-columns: repeat(2, minmax(100px, 1fr));
      //grid-gap: 10px;
      display: flex;
      align-items: baseline;

      .section-content-item-label {
        text-align: right;
        white-space: nowrap;
      }

      .section-content-item-content {
        width: 100%;
      }

      &.full-width {
        grid-column: 1 / -1;
      }
    }
  }
}

.applyScope-content {
  .applyScope-content-item {
    margin-top: 20px;
    display: flex;
    align-items: center;

    .applyScope-content-item-title {
      margin-right: 10px;
    }

    .applyScope-content-item-content {
      display: flex;
      align-items: center;

      .el-button {
        margin-right: 10px;
      }
    }
  }
}
</style>
